package com.idea.relax.launch.autoconfig;


import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.Ordered;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.ArrayList;
import java.util.List;
import java.util.ServiceLoader;
import java.util.function.Consumer;
import java.util.stream.Stream;

/**
 * @className: LaunchAutoConfigInitializer
 * @author: salad
 * @date: 2022/11/27
 **/
public class LaunchAutoConfigInitializer implements EnvironmentPostProcessor, Ordered {


	@Override
	public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
//		EnableLaunchAutoConfiguration enabledAnno = application.getMainApplicationClass().getAnnotation(EnableLaunchAutoConfiguration.class);
//		if (null == enabledAnno) {
//			return;
//		}
//		Class<? extends LaunchAutoConfigurer>[] exclude = enabledAnno.exclude();
//		Class<? extends LaunchAutoConfigurer>[] use = enabledAnno.use();
//		boolean unSet = LaunchAutoConfigurer.class == exclude[0] && LaunchAutoConfigurer.class == use[0];
//		boolean setUse = LaunchAutoConfigurer.class != use[0];
		List<LaunchAutoConfigurer> launcherList = new ArrayList<>();
//		if (unSet) {
			serviceLoad(launcherList::add);
//		} else if (setUse) {
//			serviceLoad(launcher -> {
//				if (Stream.of(use).anyMatch(u -> u.equals(launcher.getClass()))) {
//					launcherList.add(launcher);
//				}
//			});
//		} else {
//			serviceLoad(launcher -> {
//				if (Stream.of(exclude).noneMatch(e -> e.equals(launcher.getClass()))) {
//					launcherList.add(launcher);
//				}
//			});
//		}
		launcherList.forEach(launcher -> launcher.autoconfig(environment, application));

	}

	private void serviceLoad(Consumer<? super LaunchAutoConfigurer> action){
		ServiceLoader.load(LaunchAutoConfigurer.class).forEach(action);
	}


	@Override
	public int getOrder() {
		return Ordered.LOWEST_PRECEDENCE;
	}

}
